package com.pic.mgt.monitor;

import java.io.File;
import java.io.IOException;

import com.pic.mgt.log.IgxLog;
import com.pic.mgt.monitor.parser.FormatParser;
import com.pic.mgt.unit.Unit;
import com.pic.mgt.utils.LogUtils;

public abstract class UnitConverter {
	
	private FormatParser businessNamePaser;

	private Unit unit;
	protected File confirmationFile;
	
	public UnitConverter() {
		
	}
	
	public synchronized Unit parseToUnit(File confirmationFile,
							Unit unit) 
							throws IOException,
							       WrongUnitFormatException,
							       RedundantConfirmationFileException {
		this.unit = unit;
		this.confirmationFile = confirmationFile;
		
		// ********************** Log **********************
		if (IgxLog.messageDetailsLog.isDebugMode()) {
			IgxLog.messageDetailsLog.debug(this, "Converting to unit for confirmation file '{}'.",
					confirmationFile.getName());
		}
		// ********************** Log **********************
		
		// 分析並填入單元的內容(第一層級)
		doFill();
		
		// 分析並填入單元型態的內容 (第二層級)
		try {
			// throws WrongUnitFormatException, IOException
			parseUnitTypeContent(this.unit);
		} catch (WrongUnitFormatException e1) {
			LogUtils.error(this, IgxLog.messageDetailsLog, e1);
			
			throw e1;
		} catch (IOException e2) {
			if (IgxLog.messageDetailsLog.isDebugMode()) {
				IgxLog.messageDetailsLog.debug(this, "An I/O error occured for confirmation file '{}'.",
						confirmationFile.getName());
			}
			
			throw e2;
		}
		
		// ********************** Log **********************
		if (IgxLog.messageDetailsLog.isDebugMode()) {
			IgxLog.messageDetailsLog.debug(this, "Converting to unit for confirmation file '{}'completed.",
					confirmationFile.getName());
		}
		// ********************** Log **********************
		
		return this.unit;
	}
	
	/*
	 * 放入業務內容資訊:
	 * (1) confirmation file
	 * (2) Business Name
	 */
	private void doFill() throws WrongUnitFormatException {
		// --------------------- (1) confirmation file ---------------------
		fillConfirmationFile();
		
		// --------------------- (2) Business Name ---------------------
		fillBusinessName();
	}
	
	private void fillConfirmationFile() {
		this.unit.setConfirmationFile(this.confirmationFile);
	}
	
	private void fillBusinessName() throws WrongUnitFormatException {
		String businessName = (String)
								this.businessNamePaser.
									parse(this.confirmationFile.getName());
		this.unit.setBusinessName(businessName);
	}
	
	protected abstract void parseUnitTypeContent(Unit unit)
						throws IOException, WrongUnitFormatException,
							   RedundantConfirmationFileException;
	
	// --- getter and setter ---
	
	
	public void setBusinessNamePaser(FormatParser businessNamePaser) {
		this.businessNamePaser = businessNamePaser;
	}
	
}
